<template>
  <view :class="classNameList">
    <template v-if="showSubsidy">
      <view class="subsidy-price-bar">
        <view class="left">
          <view class="final-price">
            <view class="prefix">最低到手 ¥</view>
            <view class="amount" :data-value="subsidyPrice.suffix">{{ subsidyPrice.prefix }}</view>
          </view>
          <view class="discount">
            <view class="amount">已补贴{{subsidyAmount}}元</view>
            <view class="original">即将恢复¥{{pagePrice}}</view>
          </view>
        </view>
        <view class="right">
          <view>超值补贴</view>
          <view class="ul countdown">
            <view class="li">{{countdownData.minute}}</view>
            <view class="delimiter">:</view>
            <view class="li">{{countdownData.second}}</view>
            <view class="delimiter">:</view>
            <view class="li">
              <template v-if="countdownData.remain === 0">00</template>
              <view v-else class="millisecond">
                <x-image src="/assets/images/countdown-hui.gif" mode="widthFix" />
              </view>
            </view>
            <x-countdown
              v-if="showCountdown"
              :time="300000"
              auto
              @change="handleCountdownChange"
            />
          </view>
        </view>
      </view>
      <view v-if="hotSales" class="_sales">{{sales}}</view>
    </template>
    <template v-else>
      <view v-if="priceModule" class="price-box">
        <div class="price-item">
          <view class="price">
            <view v-if="crossedPrice" class="original-price">
              ¥{{ pageHighPrice }}
            </view>
            <view class="pay-price">
              <view class="price-name">实付:</view>
              <view class="price-value" :data-value="payPrice.suffix">
                {{ payPrice.prefix }}
              </view>
            </view>
          </view>
          <view v-if="hotSales" class="sales">{{sales}}</view>
        </div>

        <view class="slogan">限时促销</view>
      </view>
    </template>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import XImage from '@/components/x-image';
import XCountdown from '@/components/x-countdown';

export default {
  name: 'PPrice2',
  components: {
    XImage,
    XCountdown
  },
  props: {
    query: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showCountdown: true,
      countdownData: {}
    };
  },
  computed: {
    ...mapState({
      // 页面销量
      pageSales: state => state['product'].pageDetail.pageSales,
      // 销量模块
      hotSales: state => state['product'].pageModule.hotSales,
      // 划线价
      crossedPrice: state => state['product'].pageModule.crossedPrice,
      // 页面价格
      pagePrice: state => state['product'].pageDetail.pagePrice,
      // 页面单买价
      pageHighPrice: state => state['product'].pageDetail.pageHighPrice,
      // 价格模块
      priceModule: state => state['product'].pageModule?.price,
      // 超值补贴模块
      superSubsidyModule: state => state['product'].pageModule?.superSubsidy,
      // 商品可用优惠券
      couponList: state => state['product'].couponList,
      // 用户当前选择的优惠券信息
      userSelectCoupon: state => state['product'].userSelectCoupon,
      // 规格模式：1-统一规格；2-多规格；3-套餐模式
      skuMode: state => state['product'].productDetail?.skuMode,
      // 用户挽留弹框配置的优惠数组
      exitPopupList: state => state['pages'].exitPopupList,
      // 用户挽留弹框配置的优惠展示过的下标
      exitPopupIndex: state => state['pages'].exitPopupIndex
    }),
    classNameList() {
      const arr = ['p-price'];
      if (this.showSubsidy) {
        arr.push('is-subsidy');
      } else {
        arr.push('is-default');
      }
      if (!this.priceModule && !this.hotSales && !this.isSuperSubsidy) {
        arr.push('is-empty');
      }
      return arr.join(' ');
    },
    sales() {
      if (this.hotSales) {
        const val = this.$tools.formatNumber(this.pageSales + this.hotSales.value);
        return `已售${this.$tools.numberFormat(val)}${val >= 10000 ? '+' : ''}件`;
      } else {
        return '';
      }
    },
    // 大促展示样式
    isPromotion() {
      return !!(this.priceModule && this.priceModule?.value === 2);
    },
    // 超值补贴样式
    isSuperSubsidy() {
      return this.superSubsidyModule;
    },
    // 大促金额
    promotionDiscountAmount() {
      return this.isPromotion ? this.priceModule?.discountAmount : 0;
    },
    // 超值补贴金额
    subsidyAmount() {
      return this.isSuperSubsidy ? this.isSuperSubsidy?.value : 0;
    },
    // 商品原价
    originalPrice() {
      const arr = this.$tools.formatZero(this.pagePrice).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: this.pagePrice,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 大促底价
    promotionPrice() {
      // 当前商品售价为大促后的价格，若有挽回逻辑，在大促的金额上减去挽回金额
      // 原价 - 大促 - (优惠券 || 挽回金额)，优先优惠券
      let price = this.$tools.formatNumber(this.pagePrice - this.promotionDiscountAmount);
      // 有优惠券的时候，这里不减挽回金额
      if (this.currentExitPopup) {
        price = this.$tools.formatNumber(price - this.currentExitPopup.discountAmount);
      } else if (this.query.discountAmount) {
        price = this.$tools.formatNumber(price - this.query.discountAmount);
      } else if (this.coupon) {
        // 原价 - 大促 - 优惠券
        const coupon = this.coupon;
        if (coupon.couponType === 2) {
          // 直减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        } else if (price >= coupon.transactionAmount) {
          // 满减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        }
      }
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[0] === '0' && arr[1] === '00' ? '01' : arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 当前挽留弹窗数据
    currentExitPopup() {
      return this.query.source === 'stay' && this.exitPopupList?.length ? this.exitPopupList[this.exitPopupIndex - 1] : null;
    },
    // 优惠券
    coupon() {
      if (this.userSelectCoupon && this.couponList && this.couponList.length) {
        // 原价 - 大促 - 优惠券
        const couponList = this.couponList;
        return couponList.sort((a, b) => {
          return b.couponAmount - a.couponAmount;
        })[0];
      } else {
        return null;
      }
    },
    // 最终支付价
    payPrice() {
      // 计算逻辑为先大促再用券（满减券需在大促后计算是否满足用券条件）
      let price = this.promotionPrice.value;
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 补贴价
    subsidyPrice() {
      let price = this.$tools.formatNumber(this.pagePrice - this.subsidyAmount);
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[0] === '0' && arr[1] === '00' ? '01' : arr[1]}`);
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },

    showSubsidy() {
      return this.isSuperSubsidy && !this.currentExitPopup && !this.query.discountAmount && !this.isFromCouponCards;
    },

    isFromCouponCards() {
      return ['1008'].includes(this.query.source);
    }
  },
  watch: {},
  created() {

  },
  methods: {
    handleCountdownChange(res) {
      this.countdownData = res;
      if (res.remain === 0) {
        this.showCountdown = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .p-price{
    background: #fff;
    padding: 24px;
    border-radius: 40px 40px 0 0;
    // 默认
    &.is-default{
      .price-box{
        padding: 20px;
        background: #FDEFF4;
        border-radius: 36px;

        .price-item{
          display: flex;
          align-items: center;
          justify-content: space-between;
          .price{
            display: flex;
            align-items: center;
            .original-price{
              font-size: 40px;
              color: #999999;
              text-decoration: line-through;
              margin-right: 10px;
            }

            .pay-price{
              display: flex; align-items: flex-end; font-size: 50px;
              background: #FF0F3C;
              border-radius: 30px;
              padding: 0 28px;
              color: #FFFFFF;

              .price-name{ font-size: 24px;line-height: 46px}
              .price-value{
                font-size: 40px;
                &:before{ content: '￥'; font-size: 24px;}
                &:after{ content: attr(data-value); font-size: 24px; font-weight: normal;}
              }
            }
          }
          .sales{ color: #999999; font-size: 24px;}
        }
      }
      .slogan{
        color: #FF0F3C;
        font-size: 24px;
        margin-top: 10px;
      }
    }

    // 超值特购
    &.is-subsidy{
      .subsidy-price-bar {
        background: cdn('/images/open-banner-bg-new.jpg') no-repeat;
        background-size: cover;
        position: relative;
        display: flex;
        width: 100%;
        color: #FFFFFF;
        height: 138px;
        border-radius: 30px;
        padding: 30px 12px;

        .left{
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .final-price{
            display: flex;
            align-items: baseline;
            .prefix{
              font-size: 30px;
            }
            .amount{
              font-size: 56px;
              display: flex; align-items: baseline;
              &:after{ content: attr(data-value);
                font-size: 30px; padding-bottom: 3px; font-weight: normal;}
            }
          }

          .discount{
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding-right: 40px;
            .amount{
              flex: none;
              border-radius: 20px;
              padding: 1px 16px;
              background: #FFFFFF;
              color: #E92828;
              font-size: 24px;
              text-align: center;
              margin-bottom: 10px;
            }
            .original{
              font-size: 24px;
            }
          }
        }

        .right{
          text-align: right;
          color: #9B542E;
          font-size: 26px;
          width: 160px;
          display: flex;
          flex-direction: column;
          justify-content: center;
        }
      }

      ._sales{ color: #646464; font-size: 24px; padding: 20px 0 0; text-align: right;}

      .countdown{
        display: flex;
        justify-content: flex-end;
        color: #9B542E;
        font-size: 26px;
        margin-top: 10px;
        .li{
          width: 35px;
          height: 35px;
          background: #9B542E;
          color: #FFFFFF;
          border-radius: 8px;
          text-align: center;
          &:nth-child(5){
            position: relative;
            .millisecond{
              width: 100%;
              position: absolute;
              top: 50%;
              transform: translateY(-50%);
              filter: brightness(100);
            }
          }
        }
        .delimiter{
          margin: 0 8px;
        }
      }
    }

    // 无内容
    &.is-empty{ padding: 20px 0 20px 0;}
  }
</style>
